package pl.enigmatic.parser.xml;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;


public class PublicPropertyGetter implements PropertyGetter {

	protected final Parser<?> owner;
	private final Map<String, Field> fields = new HashMap<String, Field>();

	public PublicPropertyGetter(final Parser<?> parser) {
		owner = parser;
		for (final Field f : parser.getClazz().getDeclaredFields()) {
			final int mod = f.getModifiers();
			if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
				fields.put(f.getName(), f);
			}
		}
	}

	@Override
	public Class<?> getPropertyType(final String property) {
		if (fields.containsKey(property)) {
			return fields.get(property).getType();
		} else {
			return null;
		}
	}

	@Override
	public Object getPropertyValue(final Object target, final String property) {
		try {
			return fields.get(property).get(target);
		} catch (final Exception e) {
			return null;
		}
	}

}
